import React, { PureComponent } from 'react';
import { Spin, Modal } from 'antd';

const defaultStyle = {
  borderRadius: 5,
  borderWidth: 1,
  borderStyle: 'solid',
  borderColor: '#d9d9d9',
  width: 70,
  height: 70,
  padding: 5,
  cursor: 'pointer',
  display: 'inline-flex',
  justifyContent: 'center',
  alignItems: 'center',
};

class ImageView extends PureComponent {
  state = {
    loading: true,
    visible: false,
    imgWidth: 0,
    imgHeight: 0,
  };

  componentDidMount() {
    this.init();
  }

  componentWillReceiveProps(nextProps) {
    const { url } = this.props;
    if (url !== nextProps.url) {
      this.init();
    }
  }

  init = () => {
    const { url } = this.props;
    if (url) {
      this.setState({ loading: true });
      const image = new Image();
      image.src = url;
      if (image.complete) {
        const size = this.getImageSize(image.width, image.height);
        this.setState({ loading: false, imgWidth: size.width, imgHeight: size.height });
      } else {
        image.onload = () => {
          const size = this.getImageSize(image.width, image.height);
          this.setState({ loading: false, imgWidth: size.width, imgHeight: size.height });
        };
      }
    }
  };

  getImageSize = (originImgWidth, originImgHeight) => {
    const { width, height } = this.props;
    const divWidth = (width || defaultStyle.width) - 2 * defaultStyle.padding;
    const divHeight = (height || defaultStyle.height) - 2 * defaultStyle.padding;
    const ratio = this.getRatio(originImgWidth, originImgHeight);
    const imgWidth = originImgWidth > originImgHeight ? divWidth : divWidth * ratio;
    const imgHeight = originImgHeight > originImgWidth ? divHeight : divHeight * ratio;
    return { width: imgWidth, height: imgHeight };
  };

  getRatio = (width, height) => (width < height ? width / height : height / width);

  render() {
    const { url, style } = this.props;
    const { loading, visible, imgWidth, imgHeight } = this.state;
    return (
      <span>
        {url ? (
          <span style={{ ...defaultStyle, ...style }}>
            {loading ? (
              <Spin />
            ) : (
              <img
                style={{ width: imgWidth, height: imgHeight }}
                alt="点击预览图片"
                src={url}
                onClick={() => {
                  this.setState({ visible: true });
                }}
              />
            )}
            <Modal
              style={{ top: 20 }}
              visible={visible}
              footer={null}
              onCancel={() => {
                this.setState({ visible: false });
              }}
            >
              <img alt="" style={{ width: '100%' }} src={url} />
            </Modal>
          </span>
        ) : (
          '无'
        )}
      </span>
    );
  }
}

export default ImageView;
